// pages/login/login.js
var app = getApp();
Page({
  data: {

  },
  toggle(type, val) {
    this.setData({
      [type]: val
    });
  },
  wxGetUserProfile: function () {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        lang: 'zh_CN',
        desc: '填充您的默认下单信息',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  wxGetUserPhone: function () {
    return new Promise((resolve, reject) => {
      wx.getUserProfile({
        lang: 'zh_CN',
        desc: '填充您的默认下单信息',
        success: (res) => {
          resolve(res)
        },
        fail: (err) => {
          reject(err)
        }
      })
    })
  },
  wxSilentLogin: function () {
    return new Promise((resolve, reject) => {
      wx.login({
        success(res) {
          resolve(res.code)
        },
        fail(err) {
          reject(err)
        }
      })
    })
  },
  getByCode(userCode, callback) {
    this.req({
      url: "/wx/user/" + app.globalData.appId + "/login",
      data: {
        code: userCode
      },
      success(res) {
        if (200 == res.code && "code" == res.result.type) {
          let d = res.result.data;
          d.code = userCode;
          callback(d)
        } else {
          app.showToast({
            title: '登录成功',
            success() {
              wx.navigateBack({
                delta: 1,
              })
            }
          })
        }
      }
    })
  },
  pustUserInfo() {
    let that = this;
    let o = that.data.userData;
    console.log(o);
    let d = {
      cusName: o.nickName,
      avatarUrl: o.avatarUrl,
      gender: o.gender,
      country: o.country,
      province: o.province,
      city: o.city,
      openId: o.openid,
      unionId: o.unionid,
      cusTel: "18612461741",
      cusEmail: "ufwh@163.com",
      cusKtz: "",
      cusCompany: "",
      cusAddress: ""
    }
    wx.setStorageSync('userData', d)
    wx.navigateTo({
      url: '/pages/my/myEdit/myEdit?type=1',
    })
   
  },
  saveUser(d) {
    let that = this;
    // that.toggle("hasUserData", true);
    that.toggle("userData", d);
    this.pustUserInfo();
    // app.showToast({
    //   title: '获取成功,需要您授权手机号',
    //   icon: 'none',
    //   success() {
    //     that.toggle("hasUserData", true);
    //     that.toggle("userData", d);
    //   }
    // })
  },
  getUserPhone(e) {
    let that = this;
    let p1 = this.wxSilentLogin()
    Promise.all([p1]).then((res) => {
      that.getByCode(res[0], function (d1) {
        that.req({
          url: '/wx/user/' + app.globalData.appId + '/phone',
          data: {
            code: d1.code,
            sessionKey: d1.sessionKey,
            iv: e.iv,
            encryptedData: e.encryptedData,
            rawData: e.rawData,
            signature: e.signature
          },
          method: 'GET',
          success: function (res) {
            if (res.code === 200) {
              let data = res.result;
              for (let i in d1) {
                data[i] = d1[i];
              }
              that.saveUser(data);
            }
          }
        });
      })

    }).catch((err) => {
      console.log(err)
    })
  },
  getUserProfile(e) {
    let that = this;
    let p1 = this.wxSilentLogin()
    let p2 = this.wxGetUserProfile()
    Promise.all([p1, p2]).then((res) => {
      let d2 = res[1];
      that.getByCode(res[0], function (d1) {
        that.req({
          url: '/wx/user/' + app.globalData.appId + '/info',
          data: {
            encryptedData: d2.encryptedData,
            iv: d2.iv,
            code: d1.code,
            rawData: d2.rawData,
            sessionKey: d1.sessionKey,
            signature: d2.signature
          },
          method: 'GET',
          success: function (res) {
            if (res.code === 200) {
              let data = res.result;
              for (let i in d1) {
                data[i] = d1[i];
              }
              that.saveUser(data);
            }
          }
        });
      })

    }).catch((err) => {
      console.log(err)
    })
  },
  req: function (cfg) {
    wx.showLoading({
      title: '加载中',
    })
    wx.request({
      url: cfg.purl ? cfg.purl : app.globalData.url + cfg.url,
      data: cfg.data,
      method: cfg.method ? cfg.method : 'GET',
      success: function (res) {
        if (res && res.statusCode == 200) {
          cfg.success(res.data);
        } else {
          wx.showToast({
            title: '请求失败',
          })
        }
      },
      fail: function (a) {
        wx.showToast({
          title: '请求失败，请稍后再试',
          icon: "none"
        })
      },
      complete: function () {
        wx.hideLoading();
        wx.stopPullDownRefresh();
      }
    });
  }
})